package web.servlet;

import domain.Account;
import domain.Cart;
import domain.Order;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class NewOrderFormServlet extends HttpServlet {
    private static final String NEW_ORDER_FORM = "/WEB-INF/jsp/order/newOrderForm.jsp";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Account loginAccount = (Account) session.getAttribute("loginAccount");

        //获得购物车
        Cart cart = (Cart) session.getAttribute("cart");
        if(cart == null){
            cart = new Cart();
            session.setAttribute("cart",cart);
        }
        if(loginAccount == null){//用户未登录，请求重定向，产生新的请求，所有资源都将清空
            resp.sendRedirect("signOnForm");
        }else {//用户已登录，则产生新订单
            Order order = new Order();
            order.initOrder(loginAccount,cart);

            //向newOrderForm.jsp页面中通过会话传入两个键值对
            session.setAttribute("creditCardTypes",order.getCardType());
            session.setAttribute("order",order);

            req.getRequestDispatcher(NEW_ORDER_FORM).forward(req,resp);
        }
    }
}
